//
//  CreateAccountView.swift
//  JLDiaryApp
//
//  Created by Jiang Chencheng on 2024/9/24.
//

import SwiftUI
import AlertToast

struct SignupView: View {
    
    @Environment(\.dismiss) var dismiss
    
    @EnvironmentObject var user: UserCenter
    
    @StateObject var viewModel = SignupViewModel()
    
    var body: some View {
       
        VStack {
            Text("Create your account")
                .frame(maxWidth: .infinity, alignment: .leading)
                .foregroundColor(Color.white)
                .font(.title2)
                .fontWeight(.bold)
                .padding()
            
            // Email
            HStack {
                Image(systemName: "envelope")
                    .frame(width: 20, height: 20)
                TextField("", text: $viewModel.email, prompt: Text("Email").foregroundColor(.gray))
            }
            .modifier(JLCapsuleTextFieldModifier())
            .padding(.horizontal)
            
            // Password
            HStack {
                Image(systemName: "lock")
                    .frame(width: 20, height: 20)
                SecureField("", text: $viewModel.password, prompt: Text("Password").foregroundColor(.gray))
                    .textContentType(.password)
            }
            .modifier(JLCapsuleTextFieldModifier())
            .padding(.horizontal)
            
            
            Spacer()
            
            Button {
                viewModel.signup()
            } label: {
                Text("Sign up")
            }
            .buttonStyle(JLMainButtonStyle())
            .padding(.horizontal)
            .padding(.bottom)

        }
        .background(Color("BackgroundColor"))
        .navigationBarBackButtonHidden()
        .toolbar {
            ToolbarItem(placement: .topBarLeading) {
                Button(action: {
                    dismiss()
                }, label: {
                    HStack(spacing: 5) {
                        Image(systemName: "chevron.backward")
                            .font(.callout.bold())
                            .foregroundStyle(.white)
                    }
                })
            }
        }
        .toast(isPresenting: $viewModel.isLoading) {
            AlertToast(displayMode: .alert, type: .loading)
        }
        .toast(isPresenting: $viewModel.isError) {
            AlertToast(displayMode: .alert, type: .regular, title: viewModel.toastTitle)
        }
        .onAppear {
            viewModel.setup(user)
        }
        
    }
    
}



#Preview {
    NavigationView {
        SignupView()
    }
   
}
